package com.ibeeking.found.open.b.rest.service.impl;

import com.ibeeking.found.common.constants.WxOpenServiceTypeConstant;
import com.ibeeking.found.common.entity.open.*;
import com.ibeeking.found.common.enums.AliPayOpenAppTypeEnum;
import com.ibeeking.found.common.enums.OpenApiConfigEnum;
import com.ibeeking.found.common.enums.WxOpenAppTypeEnum;
import com.ibeeking.found.common.utils.DataUtils;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.gmc.global.api.feign.GlobalOpenFeignClient;
import com.ibeeking.found.open.b.rest.service.IAliPayOpenEventService;
import com.ibeeking.found.open.b.rest.service.IOpenService;
import com.ibeeking.found.open.service.common.param.QueryOpenAuthInfoParam;
import com.ibeeking.found.open.service.common.vo.OpenAuthVO;
import com.ibeeking.found.open.service.common.vo.UrlVO;
import com.ibeeking.found.open.service.config.OpenAuthCallBackConfig;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.file.oss.dto.OssPolicyDto;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import me.chanjar.weixin.open.api.WxOpenComponentService;
import me.chanjar.weixin.open.api.WxOpenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName AliPayOpenEventServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-06-18 12:21
 **/
@Service("aliPayOpenEventServiceImpl")
public class AliPayOpenEventServiceImpl implements IAliPayOpenEventService {
    private static final Logger log = LoggerFactory.getLogger(AliPayOpenEventServiceImpl.class);

    //2分钟
    private static final Long TIME = 30 * 60 *1000L;

    @Resource
    private GlobalOpenFeignClient globalOpenFeignClient;

    @Resource
    private IOpenService openServiceImpl;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private OpenAuthCallBackConfig openAuthCallBackConfig;

    @Override
    public String checkSignature(HttpServletRequest request, HttpServletResponse response, String content, String sign,String publicKey, String charset,String signType) {

        String out = null;

        return out;
    }

    @Override
    public Object msgEvent(HttpServletRequest request, HttpServletResponse response) {
        String out = null;

        return out;
    }
    /**
     * 授权注册页面扫码授权   显示二维码
     *
     * @param request
     * @return
     * @throws Exception
     * @Author ibeeking
     */
    @Override
    public UrlVO getPreAuthUrl(HttpServletRequest request, Integer type) throws Exception {
        String tenantId = UserUtils.getTenantId();
        OpenConfigDTO openConfigDTO = queryOpenConfigOfAliPayOpen();
        String componentAppId = openConfigDTO.getComponentAppId();
        DataUtils.trueThrowException(StringUtils.isBlank(componentAppId), "系统异常:支付宝第三放平台appId为空!");
        String aliPayAuthRedirectUrl = "";
        if (AliPayOpenAppTypeEnum.ALIPAY_OPEN_APP_TYPE_TP.getCode().equals(type)) {
            aliPayAuthRedirectUrl = openAuthCallBackConfig.getAliPayAuthRedirectUrl();
        }
        DataUtils.trueThrowException(StringUtils.isBlank(aliPayAuthRedirectUrl), "支付宝第三方授权后的跳转页面尚未配置!");
        if(StringUtils.isNotEmpty(tenantId)){
            String key = "tenant:".concat(componentAppId).concat(":").concat(type.toString());
            redisUtils.set(key, tenantId);
        }
        aliPayAuthRedirectUrl = aliPayAuthRedirectUrl + "?componentAppId=" + componentAppId + "&type=" + type;
        WxOpenService wxOpenService = openServiceImpl.getWxOpenService(componentAppId);
        if(null == wxOpenService) throw new BusinessException("支付宝开放平台服务初始化还未完成，请稍候再试");
        WxOpenComponentService wxOpenComponentService = wxOpenService.getWxOpenComponentService();
        if(null == wxOpenComponentService) throw new BusinessException("支付宝开放平台服务初始化还未完成，请稍候再试");
        String url = wxOpenComponentService.getPreAuthUrl(aliPayAuthRedirectUrl);
        return new UrlVO().setUrl(url);
    }

    @Override
    public OpenAuthVO queryOrUpdateOpenAuthInfo(QueryOpenAuthInfoParam param) throws Exception {
        String tenantId = param.getTenantId();
        String openAppId = param.getOpenAppId();
        String appId = param.getAppId();
        String componentAppId = param.getComponentAppId();
        String authCode = param.getAuthCode();
        String expiresIn = param.getExpiresIn();
        Integer serviceType =  param.getType();
        if(StringUtils.isEmpty(tenantId))
            tenantId = UserUtils.getTenantId();

        if(StringUtils.isEmpty(tenantId)){
            DataUtils.trueThrowException(true, "获取租户tenantId失败:" + tenantId);
        }

        OpenAuthDTO wxOpenAuthDTO = null;
        OpenAuthOfExtend openAuthOfExtend = null;

        OpenAuthVO openAuthVO = JsonUtils.fromJson(wxOpenAuthDTO, OpenAuthVO.class);
        if(openAuthOfExtend!=null) {
            openAuthVO.setOpenAuthOfExtend(openAuthOfExtend);
        }
        return openAuthVO;
    }

    private OpenConfigDTO queryOpenConfigOfAliPayOpen() {
        OpenConfigQuery query = new OpenConfigQuery();
        query.setType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_ALIPAY_OPEN.getCode());
        query.setSubType(AliPayOpenAppTypeEnum.ALIPAY_OPEN_APP_TYPE_TP.getCode());
        ResponseResult<OpenConfigDTO> responseResult = globalOpenFeignClient.queryOpenConfigOne(query);
        return responseResult.getData();
    }

}
